<template>
    <div class="design-item">
        <div class="design-item-controller">
            <!-- 默认的 -->
            <div class="design-item-controller-handle" v-if="isEmptyCard">
                <div class="design-default-preview">
                    <div class="design-default-preview-title">点击编辑图片广告</div>
                    <div class="design-default-preview-tip">建议宽度750像素</div>
                </div>
            </div>
            <!-- 有内容的预览 -->
            <div class="design-item-controller-handle">
                <!-- 除了345 模板类型的-->
                <div class="design-cube-preview" v-if="!isEmptyCard && [4,5].indexOf(currentTemplateId) < 0 " :style="{ width:(currentItemWidth * layoutWidth +imageBorderWidth)+'px' ,height: (currentItemHeight * layoutHeight + previewMargin)  +'px' , margin: '-' + previewMargin +'px'}">
                    <div v-if="currentLayoutArray.length" v-for="(item , index ) in currentLayoutArray" :class="['cube-selected',{'cube-selected-click':index == currentLayoutIndex}]" @click="bindSelectLayout(index)" :style="getPreviewLayoutStyle(item.style , index)">
                    </div>
                </div>
                <!-- end 除了345 模板类型的-->

                <!-- 4 模板类型的 -->
                <div style="width:320px"
                     :class="['design-cube-preview','design-cube-preview-temp-' + currentTemplateId]"
                     v-if="!isEmptyCard && currentTemplateId == 4 ">
                    <div v-for="(item , index ) in cardList"
                         v-if="cardList.length && index == 0 "
                         :class="['first',{'cube-selected-click':index == currentLayoutIndex}]"
                    >
                        <img :src="item.filesNameUrl" style="width: 100% ;height: auto;">
                    </div>
                    <div :class="['other',{'cube-selected-click':index == currentLayoutIndex}]">
                        <img v-for="(item , index ) in cardList" v-if="cardList.length && index > 0" :src="item.filesNameUrl" style="width: 100% ;height: auto;">
                    </div>
                </div>
                <!-- end 4 模板类型的 -->
                <!-- 5 模板类型的 -->
                <div style="width:320px"
                     :class="['design-cube-preview','design-cube-preview-temp-' + currentTemplateId]"
                     v-if="!isEmptyCard && currentTemplateId == 5 ">
                    <div v-for="(item , index ) in cardList"
                         v-if="cardList.length && index == 0 "
                         :class="['first',{'cube-selected-click':index == currentLayoutIndex}]">
                        <img :src="item.filesNameUrl" style="width: 100% ;height: auto;">
                    </div>

                    <div :class="['other',{'cube-selected-click':index == currentLayoutIndex}]" >
                        <div v-for="(item , index ) in cardList" v-if="cardList.length && index > 0" class="img-wrap">
                            <img :src="item.filesNameUrl" style="width: 100% ;height: auto;">
                        </div>
                    </div>
                </div>
                    <!-- end 5 模板类型的 -->
            </div>
            <slot name="menu"></slot>
        </div>
        <div class="design-item-editor" v-show="show && !showAddMenuGroup">
            <div class="design-item-editor-title">魔方</div>
            <!--模板选择-->
            <div class="editor-group">
                <div class="editor-group-label editor-group-label-top">选择模板：</div>
                <div class="editor-group-control">
                    <div class="design-select-templates" v-for="(item , index ) in templateArray" :class="{'active' : currentTemplateId == index}" @click="bindSelectTemplate(index)">
                        <div class="design-select-templates-image">
                            <span :class="['template-image' , 'cube-template-image-'+index]"></span>
                        </div>
                        <div class="design-select-templates-title">{{item.name}}</div>
                    </div>
                </div>
            </div>
            <!--自定义魔方密度-->
            <div class="editor-group" v-show="currentTemplateId == 7">
                <div class="editor-group-label">魔方密度：</div>
                <div class="editor-group-control">
                    <nc-select @change="bindChangeWidthAndHeight" :currentSelectValue="layoutWidth">
                        <option value="4">4X4</option>
                        <option value="5">5X5</option>
                        <option value="6">6X6</option>
                        <option value="7">7X7</option>
                    </nc-select>
                </div>
            </div>
            <!--布局-->
            <div class="editor-group">
                <div class="editor-group-label editor-group-label-top">布局：</div>
                <div class="editor-group-control">
                    <div class="design-component-cube clearfix" ref="selectable">
                        <ul class="cube-row cube-enable" v-for="item in layoutWidth">
                            <li class="cube-item cube-enable" v-for="itemHeight in layoutHeight" :style="{width: currentItemWidth + 'px' , height: currentItemHeight + 'px'}">
                                <span class="plus-icon" :style="{ 'line-height': currentItemHeight + 'px'}">+</span>
                            </li>
                        </ul>
                        <div v-if="currentLayoutArray.length" v-for="(item , index ) in currentLayoutArray" :class="['cube-selected' ,'cube-selected-'+ currentTemplateId,{'cube-selected-click':index == currentLayoutIndex}]" @click="bindSelectLayout(index)" :style="{width :item.style.width +'px' , height:getTopStyleHeight(item)+'px' , left : item.style.left+'px' , top : item.style.top+'px'}">

                            <img v-if="getCardImage(index) && [4,5].indexOf(currentTemplateId) < 0  " :src="getCardImage(index)" alt="cubeImage" :width="item.style.width" :height="getTopStyleHeight(item)">
                            <img v-if="getCardImage(index) && [4,5].indexOf(currentTemplateId) >= 0" :src="getCardImage(index)" style="height: 100%;width: 100%">
                            <div v-if="!getCardImage(index)" class="cube-selected-text">
                                {{item.tips}}
                            </div>
                            <i class="fa fa-close design-editor-card-item-delete " v-if="currentTemplateId == 7" @click="bindRemoveCustomLayout(index)"></i>
                        </div>
                    </div>
                    <div class="editor-group-desc" v-if="currentTemplateId != 7">选定布局区域，在下方添加图片</div>
                    <div class="editor-group-desc" v-else>移动鼠标选定布局区域大小</div>
                    <div v-if="!validated" class="design-editor-control-group-error" style="margin-left: 15px;margin-top: 5px">{{errorText}}</div>
                </div>
            </div>
            <!--图片间隙 设置-->
            <!-- <div class="editor-group">
                <div class="editor-group-label">图片间隙：</div>
                <div class="editor-group-control">
                    <div class="slider">
                        <div class="slider-main">
                            <div ref="slider">
                                <div class="ui-slider-handle">
                                    <div class="slider-tips slider-tips-hide">
                                        <div class="slider-tips-inner">{{imageBorderWidth}}</div>
                                        <i class="slider-tips-arrow"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="slider-input">
                            <input type="text" v-on:input="bindSliderInput" :value="imageBorderWidth" />
                        </div>
                    </div>
                </div>
            </div> -->
            <!--图片选项卡-->
            <div class="editor-group" v-if="currentLayoutArray.length">
                <div class="editor-card">
                    <div class="editor-card-item">
                        <div class="editor-card-item-panel">
                            <div class="editor-card-item-image">
                                <div class="has-choosed-image" v-if="currentCard && currentCard.filesNameUrl">
                                    <img class="thumb-image" :src="currentCard.filesNameUrl" width="80" height="80">
                                    <span class="modify-image" @click="bindModifyImage">更换图片</span>
                                </div>
                                <div v-else @click="bindModifyImage" class="has-not-choose-image" style="width:82px;height: 82px;"><i class="fa fa-plus"></i>
                                    <div>添加图片</div>
                                </div>
                            </div>
                            <div class="editor-card-item-content">
                                <div class="control-group">
                                    <label class="control-group-container">
                                            <div class="control-group-label">链接：</div>
                                            <div class="control-group-control">
                                                <nc-link-menu @onselect="bindSelectLinkMenu" :index="index" :current-info="currentCard"></nc-link-menu>
                                            </div>
                                        </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <slot name="addMenuGroup" v-if="showAddMenuGroup"></slot>
    </div>
</template>
<script>
    import draggable from 'vuedraggable'
    import ncSelect from './select.vue'
    import ncLinkMenu from './link-menu.vue'
    function selectRange(currentPos) {
        var xMin = currentPos.x,
            xMax = currentPos.x + currentPos.width,
            yMin = currentPos.y,
            yMax = currentPos.y + currentPos.height,
            r = []
        for (var i = xMin; i <= xMax; i++) {
            for (var j = yMin; j <= yMax; j++) {
                r.push({
                    x: i,
                    y: j
                })
            }
        }
        return r
    }
    /**
     * 碰撞检测
     */
    function isCollision(rect1, rect2) {
        console.log('碰撞检测 isCollision', rect1, rect2)
        var x1 = rect1.x,
            y1 = rect1.y,
            w1 = rect1.width,
            h1 = rect1.height,
            x2 = rect2.x,
            y2 = rect2.y,
            w2 = rect2.width,
            h2 = rect2.height
        return !((x1 + w1) < x2 || (x2 + w2) < x1 || (y1 + h1) < y2 || (y2 + h2) < y1)
    }
    const cardItemObjExample = {
        filesNameUrl: '',
        filesName: '',
        linkType: '',
        linkValue: '',
        linkValueName: '',
        linkTypeName: '',
        title: '',
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        imageWidth: 0,
        imageHeight: 0
    }
    const templateArray = [{
            name: '1行2个',
            tips: '建议尺寸 750x350 像素',
            showMethod: 0,
            layoutHeight: 1,
            layoutWidth: 2,
            picMax: 2,
            itemWidth: 160,
            layout: [{
                    style: {
                        width: 160,
                        height: 160,
                        top: 0,
                        left: 0
                    },
                    tips: '宽度375像素'
                },
                {
                    style: {
                        width: 160,
                        height: 160,
                        top: 0,
                        left: 160
                    },
                    tips: '宽度375像素'
                }
            ]
        },
        {
            name: '1行3个',
            tips: '建议宽度 750 像素',
            showMethod: 1,
            layoutHeight: 1,
            layoutWidth: 3,
            picMax: 3,
            itemWidth: 107,
            layout: [{
                    style: {
                        width: 107,
                        height: 107,
                        top: 0,
                        left: 0
                    },
                    tips: '宽度250像素'
                },
                {
                    style: {
                        width: 107,
                        height: 107,
                        top: 0,
                        left: 107
                    },
                    tips: '宽度250像素'
                },
                {
                    style: {
                        width: 107,
                        height: 107,
                        top: 0,
                        left: 214
                    },
                    tips: '宽度250像素'
                }
            ]
        },
        {
            name: '1行4个',
            tips: '建议宽度 750 像素',
            showMethod: 2,
            layoutHeight: 1,
            layoutWidth: 4,
            picMax: 4,
            itemWidth: 80,
            layout: [{
                    style: {
                        width: 80,
                        height: 80,
                        top: 0,
                        left: 0
                    },
                    tips: '宽度188像素'
                },
                {
                    style: {
                        width: 80,
                        height: 80,
                        top: 0,
                        left: 81
                    },
                    tips: '宽度188像素'
                },
                {
                    style: {
                        width: 80,
                        height: 80,
                        top: 0,
                        left: 162
                    },
                    tips: '宽度188像素'
                },
                {
                    style: {
                        width: 80,
                        height: 80,
                        top: 0,
                        left: 243
                    },
                    tips: '宽度188像素'
                }
            ]
        },
        {
            name: '2左2右',
            tips: '建议宽度 670 像素',
            showMethod: 3,
            layoutHeight: 2,
            layoutWidth: 2,
            picMax: 4,
            itemWidth: 161,
            layout: [{
                    style: {
                        width: 161,
                        height: 161,
                        top: 0,
                        left: 0
                    },
                    tips: '375x375像素或同等比例'
                },
                {
                    style: {
                        width: 161,
                        height: 161,
                        top: 0,
                        left: 162
                    },
                    tips: '375x375像素或同等比例'
                },
                {
                    style: {
                        width: 161,
                        height: 161,
                        top: 162,
                        left: 0
                    },
                    tips: '375x375像素或同等比例'
                },
                {
                    style: {
                        width: 161,
                        height: 161,
                        top: 162,
                        left: 162
                    },
                    tips: '375x375像素或同等比例'
                }
            ]
        },
        {
            name: '1左2右（小）',
            tips: '建议宽度 305 像素',
            showMethod: 4,
            layoutHeight: 4,
            layoutWidth: 4,
            picMax: 3,
            itemWidth: 80,
            layout: [{
                    style: {
                        width: 161,
                        height: 323,
                        top: 0,
                        left: 0
                    },
                    tips: '宽度375像素'
                },
                {
                    style: {
                        width: 161,
                        height: 161,
                        top: 0,
                        left: 162
                    },
                    tips: '宽度375像素'
                },
                {
                    style: {
                        width: 161,
                        height: 161,
                        top: 162,
                        left: 162
                    },
                    tips: '宽度375像素'
                }
            ]
        },
        {
            name: '1上2下',
            tips: '建议宽度 128 像素',
            showMethod: 5,
            layoutHeight: 4,
            layoutWidth: 4,
            picMax: 3,
            itemWidth: 80,
            layout: [{
                    style: {
                        width: 323,
                        height: 161,
                        top: 0,
                        left: 0
                    },
                    tips: '宽度750像素'
                },
                {
                    style: {
                        width: 161,
                        height: 161,
                        top: 162,
                        left: 0
                    },
                    tips: '宽度375像素'
                },
                {
                    style: {
                        width: 161,
                        height: 161,
                        top: 162,
                        left: 162
                    },
                    tips: '宽度375像素'
                }
            ]
        },
        {
            name: '1左3右',
            tips: '建议宽度 128 像素',
            showMethod: 6,
            layoutHeight: 4,
            layoutWidth: 4,
            picMax: 4,
            itemWidth: 80,
            layout: [{
                    style: {
                        width: 161,
                        height: 323,
                        top: 0,
                        left: 0
                    },
                    tips: '375x750像素或同等比例'
                },
                {
                    style: {
                        width: 161,
                        height: 161,
                        top: 0,
                        left: 162
                    },
                    tips: '375x375像素或同等比例'
                },
                {
                    style: {
                        width: 80,
                        height: 161,
                        top: 162,
                        left: 162
                    },
                    tips: '188x375像素或同等比例'
                },
                {
                    style: {
                        width: 80,
                        height: 161,
                        top: 162,
                        left: 243
                    },
                    tips: '188x375像素或同等比例'
                }
            ]
        },
        {
            name: '自定义',
            tips: '建议宽度 128 像素',
            showMethod: 7,
            layoutHeight: 4,
            layoutWidth: 4,
            picMax: 49,
            itemWidth: 80,
            layout: []
        }
    ]


    // const genCurrentLayout = function(index,imageBorderWidth){
    //     let baseWidth = (320 - imageBorderWidth) / 2 
    //     return  [{
    //                 style: {
    //                     width: baseWidth,
    //                     height: baseWidth,
    //                     top: 0,
    //                     left: 0
    //                 },
    //                 tips: '375像素或同等比例'
    //             },
    //             {
    //                 style: {
    //                     width: baseWidth,
    //                     height: baseWidth,
    //                     top: 0,
    //                     left: baseWidth +imageBorderWidth
    //                 },
    //                 tips: '375像素或同等比例'
    //             }
    //         ]
    // }


    export default {
        name: "nc-design-item-cube",
        otherInfo: {
            title: "魔方",
            type: 'cube',
            group: 0,
            max: 0
        },
        components: {
            'nc-select': ncSelect,
            'nc-link-menu': ncLinkMenu,
            draggable
        },
        props: {
            show: {
                type: Boolean,
                default: false
            },
            options: {
                type: Object,
                default: null
            },
            cid: {
                type: Number
            },
            showAddMenuGroup: {
                type: Boolean,
                default: false
            }
        },
        data() {
            let opts = !Nc.isEmpty(this.options) ?
                {
                    currentTemplateId: this.options.currentTemplateId,
                    //图片间隙
                    imageBorderWidth: this.options.imageBorderWidth,
                    // 选项卡
                    cardList: this.options.cardList,
                    layoutWidth: this.options.layoutWidth,
                    layoutHeight: this.options.layoutHeight,
                    type: 'cube',
                    isEmptyCard: false
                } :
                {
                    currentTemplateId: 0,
                    //图片间隙
                    imageBorderWidth: 0,
                    layoutWidth: 2,
                    layoutHeight: 1,
                    type: 'cube',
                    // 选项卡
                    cardList: [0, 1].map(item => {
                        return $.extend(true, {}, cardItemObjExample)
                    }),
                    isEmptyCard: true
                }
            opts.templateArray = templateArray
            opts.currentLayoutIndex = 0
            // 是否自定义可以开始
            opts.enableCustomStart = false
            // 自定义开始点和结束点坐标
            opts.customStartPos = {
                x: 0,
                y: 0
            }
            // 自定义选择区域
            opts.customSelectArea = null
            opts.customSelectArray = []
            //标识验证通过
            opts.validated = true
            opts.errorText = '请添加图片'
            return opts
        },
        computed: {
            currentTemplate() {
                // let borderWidth = this.imageBorderWidth
                // if (this.currentTemplateId == 0 ){
                //     this.templateArray[this.currentTemplateId].layout = genCurrentLayout(this.currentTemplateId ,borderWidth)
                // }
                return this.templateArray[this.currentTemplateId]
            },
            currentLayoutArray: {
                get() {
                    return this.currentTemplate.layout
                },
                set(newValue) {
                    this.templateArray[this.currentTemplateId].layout = newValue
                }
            },
            currentCard() {
                return this.cardList[this.currentLayoutIndex]
            },
            currentItemWidth() {
                let dep1 = this.layoutWidth
                if (this.currentTemplateId != 7) return this.currentTemplate.itemWidth
                let r = ''
                if (this.layoutWidth == 4) {
                    return 80
                } else if (this.layoutWidth == 5) {
                    return 63.8
                } else if (this.layoutWidth == 6) {
                    return 53
                } else {
                    return 45.2857
                }
            },
            currentItemHeight() {
                console.log('compute item height');
                if (this.currentTemplateId > 2 || this.isEmptyCard || this.cardList[0].filesName == '') {
                    return this.currentItemWidth
                }
                let currentPic = this.cardList[0]
                return Math.round((this.currentItemWidth * currentPic.imageHeight) / currentPic.imageWidth)
            },
            previewMargin() {
                return parseFloat((this.imageBorderWidth / 2).toFixed(1))
            }
        },
        watch: {
            layoutWidth(value) {
                var self = this
                this.$nextTick(function() {
                    console.log('watch layoutwidth initselectable ')
                    self.currentTemplateId == 7 && this.initSelectableState()
                })
            },
            currentTemplateId(value) {
                if (value == 7) {
                    this.$nextTick(() => {
                        this.initSelectableState()
                    })
                }
            }
        },
       
        mounted() {
            var self = this
            $(this.$refs.slider).slider({
                range: "min",
                min: 0,
                max: 30,
                slide: function(event, ui) {
                    self.imageBorderWidth = ui.value
                }
            })
            $(this.$refs.slider).slider("value", self.imageBorderWidth)
            // 装填自定义的选择区域
            if (!Nc.isEmpty(this.options) && this.currentTemplateId == 7) {
                this.initCustomLayoutData()
                this.initSelectTableEvents()
            }
        },
        methods: {
            getTopStyleHeight(item) {
                if (this.currentTemplateId > 2) return item.style.height
                return this.currentItemHeight
            },
            /**
             * 计算当前layout 高度
             */
            computeCurrentLayoutHeight(imgW, imgH) {
                var currentLayoutIndex = this.currentLayoutIndex,
                    cardInfo = this.cardList[this.currentLayoutIndex]
                if (currentLayoutIndex != 0) return
                let scale = (imgW / imgH).toFixed(3)
            },
            /**
             * 获取该组件的数据
             */
            getCurrentData() {
                return this.validated = this.validImage() ? {
                    currentTemplateId: this.currentTemplateId,
                    imageBorderWidth: this.imageBorderWidth,
                    cardList: this.cardList,
                    layoutWidth: this.layoutWidth,
                    layoutHeight: this.layoutHeight,
                    type: this.type
                } : null
            },
            /**
             * 初始化自定义的数据
             */
            initCustomLayoutData() {
                console.log('初始化自定义的数据')
                this.cardList.forEach(item => {
                    this.customSelectArray.push({
                        x: item.x,
                        y: item.y,
                        width: item.width,
                        height: item.height,
                        imageWidth: 0,
                        imageHeight: 0
                    })
                    this.addCustomLayout(item)
                })
            },
            /**
             * 重置当前cardlist
             */
            resetCardList(index) {
                var a = index == 7 ? 0 : this.currentTemplate.picMax,
                    r = []
                this.isEmptyCard = true
                for (var i = 1; i <= a; i++) {
                    r.push($.extend(true, {}, cardItemObjExample))
                }
                this.cardList = r
            },
            /**
             * 适配当前的cardlist
             */
            adapterCurrentCardList() {
                console.log('适配当前的cardlist')
                var currentCardList = this.cardList,
                    currentPicMax = this.currentTemplate.picMax
                if (currentCardList.length > currentPicMax) {
                    this.cardList.splice(currentPicMax)
                } else {
                    for (var i = this.cardList.length; i < currentPicMax; i++) {
                        this.cardList.push($.extend(true, {}, cardItemObjExample))
                    }
                }
            },
            /**
             * 初始化方块选择区域
             */
            initSelectableState() {
                console.log('初始化方块选择区域')
                this.customSelectArray = []
                this.customSelectArea = null
                this.customStartPos = {
                    x: 0,
                    y: 0
                }
                this.currentLayoutArray = []
                this.cardList = []
                this.initSelectTableEvents()
            },
            /**
             * 初始化方块选择区域事件
             */
            initSelectTableEvents() {
                var self = this,
                    elSelectable = $(this.$refs.selectable)
                // 自定义的item 点击事件
                console.log('自定义的item 点击事件')
                elSelectable.find('li').off('click').on('click', function() {
                    console.log('自定义的item 点击事件')
                    let $this = $(this)
                    if (self.enableStart) {
                        self.customSelectArray.push(self.customSelectArea)
                        self.addCustomLayout(self.customSelectArea)
                        self.cardList.push($.extend(true, {}, cardItemObjExample, self.customSelectArea))
                        elSelectable.find('li.item-selecting').removeClass('item-selecting')
                    } else {
                        self.customStartPos = {
                            x: $this.closest('ul').index(),
                            y: $this.index()
                        }
                        self.customSelectArea = {
                            x: self.customStartPos.x,
                            y: self.customStartPos.y,
                            width: 0,
                            height: 0,
                            imageWidth: 0,
                            imageHeight: 0
                        }
                        $this.addClass('item-selecting')
                    }
                    self.enableStart = !self.enableStart
                })
                // 鼠标移动后选中item
                elSelectable.find('li').off('mouseenter').on('mouseenter', function() {
                    if (!self.enableStart) return
                    console.log('li mouseenter')
                    var $this = $(this),
                        endX = $this.closest('ul').index(),
                        endY = $this.index(),
                        minX = Math.min(self.customStartPos.x, endX),
                        maxX = Math.max(self.customStartPos.x, endX),
                        minY = Math.min(self.customStartPos.y, endY),
                        maxY = Math.max(self.customStartPos.y, endY),
                        currentArea = {
                            x: minX,
                            y: minY,
                            width: maxX - minX,
                            height: maxY - minY,
                            imageWidth: 0,
                            imageHeight: 0
                        }
                    if (!self.verifyRect(currentArea) && self.enableStart) {
                        self.customSelectArea = currentArea
                    }
                    self.customChangeItem(selectRange(self.customSelectArea))
                })
                elSelectable.off('mouseleave').on('mouseleave', function() {
                    console.log('mouseleave')
                    self.enableStart = false
                    self.customSelectArea = null
                    self.customStartPos = {
                        x: 0,
                        y: 0
                    }
                    $(self.$refs.selectable).find('.item-selecting').removeClass('item-selecting')
                })
            },
            /**
             * 碰撞检测
             */
            verifyRect(currentSelectArray) {
                console.group('碰撞检测')
                console.log('移动时当前区域', currentSelectArray)
                console.log('已选区域', this.customSelectArray)
                var r = false
                $.each(this.customSelectArray, function(index, item) {
                    if (isCollision(item, currentSelectArray) || isCollision(currentSelectArray, item)) {
                        r = true
                        return
                    }
                })
                console.groupEnd()
                return r
            },
            /**
             * 自定义 选择选中item
             */
            customChangeItem(selectArray) {
                console.log('selectArray')
                var elSelectable = $(this.$refs.selectable)
                elSelectable.find('li').removeClass('item-selecting')
                selectArray.forEach(item => {
                    var el = elSelectable.find('ul:eq(' + item.x + ') li:eq(' + item.y + ')')
                    if (el.length) el.addClass('item-selecting')
                });
            },
            /**
             * 获取左边预览样式第二种，为3,4,5模板
             */
            getPreviewLayoutStyleForCenter(index){
                var result = {
                    width :'100%' ,
                    height :'auto'
                }
                switch (this.currentLayoutIndex){
                    case 4 :
                        if (index == 0 )
                        break
                }
                return result
            },

            /**
             * 获取左边预览的样式
             */
            getPreviewLayoutStyle(currentStyle, index) {
                console.log('获取左边预览的样式')
                let a = this.cardList[index],
                    gap = this.getPreviewLayoutSytleItemGap(a, index),
                    r = {
                        width: (currentStyle.width - this.previewMargin) + 'px',
                        height: ((this.currentTemplateId > 2 ? currentStyle.height : this.currentItemHeight) - this.previewMargin) + 'px',
                        left: (currentStyle.left +gap.left) + 'px',
                        top: (currentStyle.top + gap.top) + 'px',
                        margin: this.previewMargin + 'px'
                    }
                if (a && a.filesNameUrl) {
                    r.backgroundImage = 'url(' + a.filesNameUrl + ')'
                }
                return r
            },
            getPreviewLayoutSytleItemGap(info, index) {
                let currentTemplateId = this.currentLayoutIndex,
                    margin = this.previewMargin,
                    topGap = 0,
                    leftGap = 0
                if (index !== 0) {
                    switch (this.currentLayoutIndex) {
                        case 0:
                        case 1:
                        case 2:
                            {
                                topGap = 0
                                leftGap = margin
                                break;
                            }
                        default:
                            break;
                    }
                }
                return {
                    top: topGap,
                    left: leftGap
                }
            },
            getCardImage(index) {
                let a = this.cardList[index]
                return a && a.filesNameUrl ? a.filesNameUrl : null
            },
            /**
             * 添加自定义的layout
             */
            addCustomLayout(currArea) {
                let x = currArea.x + currArea.width,
                    y = currArea.y + currArea.height,
                    itemWidth = currArea.width + 1,
                    itemHeight = currArea.height + 1,
                    width = this.currentItemWidth * itemWidth + (itemWidth > 1 ? itemWidth - 1 : 0),
                    height = this.currentItemWidth * itemHeight + (itemHeight > 1 ? itemHeight - 1 : 0),
                    divLeft = currArea.x * this.currentItemWidth,
                    divTop = currArea.y * this.currentItemWidth,
                    tipsBlockSize = (750 / this.layoutWidth).toFixed(1),
                    tipsWidth = itemWidth >= this.layoutWidth ? 750 : (itemWidth * tipsBlockSize),
                    tipsHeight = itemHeight >= this.layoutHeight ? 750 : (itemHeight * tipsBlockSize)
                // console.log(`itemHeight is : ${itemHeight} ,itemWidth :${itemWidth}`)
                // console.log(`current item width is ${this.currentItemWidth}` )
                // console.log(`self.layoutHeight is ${this.layoutHeight}`)
                let a = {
                    style: {
                        width: width,
                        height: height,
                        left: (divLeft == 0 ? divLeft : divLeft + x - 1),
                        top: (divTop == 0 ? divTop : divTop + y - 1)
                    },
                    tips: Math.round(tipsWidth) + 'x' + Math.round(tipsHeight) + '像素或同等比例'
                }
                this.currentLayoutArray.push(a)
                this.currentLayoutIndex = this.currentLayoutArray.length - 1
            },
            /**
             * 验证添加图片是否完成
             */
            validImage() {
                console.groupCollapsed('验证添加图片是否完成')
                var self = this,
                    _customSelectArray = self.customSelectArray,
                    inRect = function(currentPos) {
                        console.log('inRect param ', currentPos)
                        for (let i = 0; i < _customSelectArray.length; i++) {
                            let curr = _customSelectArray[i]
                            console.log('inRect curr is ', curr)
                            if (isCollision(currentPos, curr) || isCollision(curr, currentPos)) {
                                console.log('inRect,return true')
                                return true
                            }
                        }
                        console.log('inRect,return false')
                        return false
                    },
                    validCustomImage = function() {
                        console.log('验证列是否加满')
                        var _width = self.layoutWidth,
                            _height = self.layoutHeight
                        for (var x = 0; x < _width; x++) {
                            for (var y = 0; y < _height; y++) {
                                let currentPos = {
                                    x: x,
                                    y: y,
                                    width: 0,
                                    height: 0
                                }
                                if (!inRect(currentPos)) {
                                    self.errorText = '列必须添加满'
                                    return false
                                }
                            }
                        }
                        console.log('validCustomImage , return true ')
                        return true
                    }
                let max = this.currentTemplate.picMax,
                    r = true,
                    currentCardNum = this.cardList.length
                console.log('max : ', max)
                console.log('currentCardNum is : ', currentCardNum)
                console.log('currentTemplateId is : ', this.currentTemplateId)
                this.errorText = '请添加图片'
                if (this.currentTemplateId == 7) {
                    console.log('验证自定义选取')
                    max = this.customSelectArray.length
                    console.log('当前已设置 , max : ', max)
                    if (max == 0) {
                        this.errorText = '请选定布局区域大小'
                        return false
                    }
                    if (!validCustomImage()) return false
                }
                if (currentCardNum < max) return false
                console.log('验证layout 是否都添加了图片')
                $.each(this.cardList, function(index, item) {
                    if (!item.filesName) {
                        r = false
                        return
                    }
                })
                console.groupEnd()
                return r
            },
            /**
             * 选择模板
             */
            bindSelectTemplate(index) {
                if ((this.currentTemplateId != 7 && index == 7) || (this.currentTemplateId == 7 && index != 7)) {
                    this.currentTemplateId = index
                    this.resetCardList(index)
                    this.templateArray[7].layout = []
                    this.customSelectArray = []
                    $(this.$refs.selectable).find('.item-selected').removeClass('item-selected')
                }
                this.currentTemplateId = index
                this.currentLayoutIndex = 0
                this.layoutWidth = this.currentTemplate.layoutWidth
                this.layoutHeight = this.currentTemplate.layoutHeight
                if (index != 7) {
                    console.log('裁切 cardList')
                    this.adapterCurrentCardList(index)
                }
            },
            /**
             * 选择布局
             */
            bindSelectLayout(index) {
                console.log('选择布局')
                this.currentLayoutIndex = index
            },
            /**
             * 自定义区域选择宽高
             */
            bindChangeWidthAndHeight(obj) {
                let value = parseInt(obj.value)
                this.layoutWidth = value
                this.layoutHeight = value
                this.resetCardList()
            },
            /**
             * 删除一个自定义区域
             * @param index
             */
            bindRemoveCustomLayout(index) {
                this.customSelectArray.splice(index, 1)
                this.currentLayoutArray.splice(index, 1)
                this.cardList.splice(index, 1)
                console.log(this.customSelectArray)
            },
            /**
             * 修改选中图片
             */
            bindModifyImage() {
                console.log('修改选中图片')
                var self = this,
                    cardInfo = this.cardList[this.currentLayoutIndex]
                if (!cardInfo) {
                    this.$set(this.cardList, this.currentLayoutIndex, $.extend(true, {}, cardItemObjExample))
                    cardInfo = this.cardList[this.currentLayoutIndex]
                }
                Nc.openAlbum({
                    multiSelect: false
                }, function(picList) {
                    console.log('openalbum cb ', picList)
                    let picFiles = picList[0]
                    cardInfo.filesNameUrl = picFiles.filesNameUrl
                    cardInfo.filesName = picFiles.filesName
                    self.isEmptyCard = false
                    cardInfo.imageHeight = picFiles.filesHeight
                    cardInfo.imageWidth = picFiles.filesWidth
                    self.computeCurrentLayoutHeight(picFiles.filesWidth, picFiles.filesHeight)
                })
            },
            /**
             * 修改链接类型
             * @param linkSelectInfo
             */
            bindSelectLinkMenu(linkSelectInfo) {
                console.log('修改链接类型', linkSelectInfo)
                let cardInfo = this.cardList[this.currentLayoutIndex],
                    linkInfo = linkSelectInfo.info
                if (linkInfo) {
                    cardInfo.linkType = linkInfo.linkType
                    cardInfo.linkValue = linkInfo.linkValue
                    cardInfo.linkValueName = linkInfo.linkValueName
                    cardInfo.linkTypeName = linkInfo.linkTypeName
                } else {
                    cardInfo.linkType = ''
                    cardInfo.linkValue = ''
                    cardInfo.linkValueName = ''
                    cardInfo.linkTypeName = ''
                }
            },
            bindSliderInput(event) {
                let a = $(event.target).val(),
                    b = parseInt(a.replace(/\D+/, '')),
                    r = isNaN(b) ? 0 : (b > 30 ? 30 : (b < 0 ? 0 : b))
                this.imageBorderWidth = r
                $(event.target).val(r)
            }
        }
    }
</script>